import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';

import 'package:flutter_html/flutter_html.dart';
import 'package:icons_plus/icons_plus.dart';
import 'package:super_study_language_tools/dao/dao_dictionary_word.dart';
import 'package:super_study_language_tools/event/event_param.dart';
import 'package:super_study_language_tools/service/service_user_word.dart';
import 'package:super_study_language_tools/tools/tools_common.dart';

import '../model/model_dictionary_word.dart';

class PanelDictionary extends StatefulWidget {
  const PanelDictionary({super.key});

  @override
  State<PanelDictionary> createState() => _PanelDictionaryState();
}

class _PanelDictionaryState extends State<PanelDictionary>
    with AutomaticKeepAliveClientMixin {
  // 查询列表
  List<String> queryWordStack = [];

  // 当前查询索引
  int curIndex = -1;

  TextEditingController _textEditingController = new TextEditingController();

  StreamSubscription? stream;

  ModelDictionaryWord? wd;

  TextStyle _titleStyle = TextStyle(fontSize: 18, fontWeight: FontWeight.w900);

  Map<String, ModelDictionaryWord> _dictMap = {};

  @override
  void initState() {
    super.initState();

    print('开始监听');
    stream = ToolsCommon.wordEventBus
        .on<EventParamWord>()
        .listen((EventParamWord data) async {
      print("监听到" + data.getWord);
      op_query_word(data.getWord);
      // htmlData = Mdict.query3(data.getWord);
      // wd = await DaoDictionaryWord.findByWord(data.getWord.toLowerCase());
      // print(wd);
      // setState(() {});
    });
  }

  @override
  void dispose() {
    if (stream != null) {
      stream!.cancel();
      stream = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: Column(
        children: [
          buildSearchBar(),
          queryWordStack.length > 0 ? buidlWordPanel() : buildQueryHistory()
        ],
      ),
    );
  }

  // 1. 搜索栏
  buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        decoration: BoxDecoration(
            border:
                Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                  onSubmitted: (value) {
                    op("op_query_word");
                  },
                  textAlign: TextAlign.center,
                  controller: _textEditingController,
                  autofocus: true,
                  decoration: InputDecoration(
                      hintText: "请在此处输入要查询的单词",
                      hintStyle: TextStyle(color: Colors.grey[400]),
                      border: InputBorder.none)),
            ),
            Offstage(
              offstage: _textEditingController.text.isEmpty ? true : false,
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    _textEditingController.clear(); //清除textfield的值
                  });
                },
                child: Container(
                  width: 45,
                  height: 45,
                  child: Icon(
                    Icons.cancel,
                    color: Colors.grey,
                    size: 17,
                  ),
                ),
              ),
            ),
            TextButton(
                onPressed: () {
                  op("op_query_word");
                },
                child: Text("查询"))
          ],
        ),
      ),
    );
  }

  // 2. 单词面板
  buidlWordPanel() {
    return Expanded(
        child: Container(
            // color: Colors.green,
            child: Column(children: [buildWordBar(), buildWordResult()])));
  }

  buildWordBar() {
    return Container(
      // color: Colors.red,
      height: 50,
      child: Row(
        children: [
          IconButton(
              onPressed: () {
                op("op_prev_word");
              },
              icon: Icon(Icons.keyboard_arrow_left)),
          curIndex + 1 != queryWordStack.length
              ? IconButton(
                  onPressed: () {
                    op("op_next_word");
                  },
                  icon: Icon(Icons.keyboard_arrow_right))
              : SizedBox(
                  width: 1,
                ),
          Text(queryWordStack[curIndex]),
          IconButton(
            onPressed: () {
              // 当前单词
              print("添加到单词本");
              if (wd != null && wd!.word != null) {
                ServiceUserWord.add(wd!.word!, false);
              }
            },
            icon: Icon(BoxIcons.bx_book_add),
            tooltip: "添加到单词本",
          ),
          TextButton(onPressed: () {}, child: Text("更多")),
          // IconButton(onPressed: () {}, icon: Icon(Icons.more_horiz)),
        ],
      ),
    );
  }

  buildWordResult() {
    if (wd == null) return Container();

    return Expanded(
      child: Container(
          padding: EdgeInsets.all(2),
          width: 350,
          // color: Colors.lightBlueAccent,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "[单词]",
                  style: _titleStyle,
                ),
                Text("${wd!.word!}"),
                SizedBox(
                  height: 15,
                ),
                Text(
                  "[音标]",
                  style: _titleStyle,
                ),
                Text("${wd!.soundmark!}"),
                SizedBox(
                  height: 15,
                ),
                Text(
                  "[简明]",
                  style: _titleStyle,
                ),
                Text("${wd!.explain!}"),
                SizedBox(
                  height: 15,
                ),
                // Text("${wd!.info!}")
                ...buildWordInfoHtml()
              ],
            ),
          )),
    );
  }

  buildWordInfoHtml() {
    List<Widget> widgets = [];

    var info = jsonDecode(wd!.info!);
    var sections = info['sections'];
    for (int i = 0; i < sections.length; i++) {
      var inf = sections[i];
      print(inf['name']);
      print(inf['html']);

      widgets.add(Text(
        "[${inf['name']}]",
        style: _titleStyle,
      ));
      widgets.add(Html(data: inf['html']));
    }
    return widgets;
  }

  // 3. 查询历史
  buildQueryHistory() {
    var list = _dictMap.keys;
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text("查询历史"),
          Container(
              padding: EdgeInsets.all(5),
              height: 300,
              // color: Colors.lightBlueAccent,
              child: Wrap(
                direction: Axis.horizontal,
                alignment: WrapAlignment.center,
                spacing: 15,
                runSpacing: 5,
                children: list
                    .map((v) => TextButton(
                        onPressed: () {
                          op_query_word(v);
                        },
                        child: Text(
                          v,
                          style:
                              TextStyle(fontSize: 18, color: Colors.lightBlue),
                        )))
                    .toList(),
              )
              //   ListView.builder(
              //   itemExtent: 50,
              //   itemBuilder: (context,index){
              //     return Center(child: Text(list.elementAt(index)));
              //   },
              //   itemCount: list.length
              // ),
              )
        ],
      ),
    );
  }

  void op(String s, [data]) {
    switch (s) {
      case "op_query_word":
        String word = _textEditingController.text;
        op_query_word(word);
        break;
      case "op_prev_word":
        op_prev_word();
        break;
      case "op_next_word":
        op_next_word();
        break;
    }
  }

  op_query_word(String word) async {
    print("查询" + word);
    if (word.length > 0) {
      // 清除当前查询的后续单词
      while (queryWordStack.length > curIndex + 1) {
        queryWordStack.removeLast();
      }
      // 添加到单词列表
      queryWordStack.add(word.toLowerCase());
      // 增加索引编号
      curIndex++;
      // 查询单词
      if (_dictMap[word.toLowerCase()] != null) {
        wd = _dictMap[word.toLowerCase()];
      } else {
        wd = await DaoDictionaryWord.findByWord(word.toLowerCase());
        if (wd != null) {
          _dictMap[word.toLowerCase()] = wd!;
        }
      }
      if (wd == null) {
        if (word.endsWith("s") || word.endsWith("d")) {
          String word2 = word.substring(0, word.length - 1);
          wd = await DaoDictionaryWord.findByWord(word2.toLowerCase());
          if (wd != null) {
            _dictMap[word.toLowerCase()] = wd!;
          }
        }
      }
      if (wd == null) {
        if (word.endsWith("es") || word.endsWith("ed")|| word.endsWith("'s")) {
          String word2 = word.substring(0, word.length - 2);
          wd = await DaoDictionaryWord.findByWord(word2.toLowerCase());
          if (wd != null) {
            _dictMap[word.toLowerCase()] = wd!;
          }
        }
      }
      if (wd == null) {
        if (word.endsWith("ies")) {
          String word2 = word.substring(0, word.length - 3) + "y";
          wd = await DaoDictionaryWord.findByWord(word2.toLowerCase());
          if (wd != null) {
            _dictMap[word.toLowerCase()] = wd!;
          }
        }
      }

      setState(() {});
    }
  }

  // op_query_word(String word) async {
  //   print("查询" + word);
  //   if (word.length > 0) {
  //     // 清除当前后续
  //     while (queryWordStack.length > curIndex + 1) {
  //       queryWordStack.removeLast();
  //     }
  //     // 添加到单词列表
  //     queryWordStack.add(word.toLowerCase());
  //     // 增加索引编号
  //     curIndex++;
  //     // 查询单词
  //     if (_dictMap[word.toLowerCase()] == null)
  //     {
  //       DaoDictionaryWord.findByWord(word.toLowerCase()).then((v) {
  //         print(v);
  //         if (v != null) {
  //           wd = v;
  //           _dictMap[word.toLowerCase()] = v;
  //         }
  //         else
  //         {
  //             wd = null;
  //         }
  //       });
  //     } else {
  //       wd = _dictMap[word.toLowerCase()];
  //     }
  //     setState(() {});
  //   }
  // }

  // 前一词
  void op_prev_word() {
    print("curIndex=${curIndex}");
    curIndex--;
    if (curIndex == -1) {
      while (queryWordStack.length > 0) {
        queryWordStack.removeLast();
      }
    }
    if (curIndex > -1) {
      String word = queryWordStack[curIndex];
      wd = _dictMap[word];
    }
    setState(() {});
  }

  // 后一词
  void op_next_word() {
    print("curIndex=${curIndex}");
    if (queryWordStack.length - 1 > curIndex) {
      curIndex++;
    }
    if (curIndex > -1) {
      String word = queryWordStack[curIndex];
      wd = _dictMap[word];
    }
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;
}
